//
//  SVTopScrollView.m
//  SlideView
//
//  Created by Chen Yaoqiang on 13-12-27.
//  Copyright (c) 2013年 Chen Yaoqiang. All rights reserved.
//

#import "SVTopScrollView.h"
#import "SVGloble.h"
#import "SVRootScrollView.h"


//按钮空隙
#define BUTTONGAP 5
//加号的宽度
#define ADDBUTTONWIDTH 0
#define SCROLLVIEW_X_OFFSET 0
//滑条宽度
#define CONTENTSIZEX ([UIScreen mainScreen].bounds.size.width - ADDBUTTONWIDTH - SCROLLVIEW_X_OFFSET)
//按钮id
#define BUTTONID (sender.tag-100)
//滑动id
#define BUTTONSELECTEDID (scrollViewSelectedChannelID - 100)




@interface SVTopScrollView()

@property(nonatomic,assign) CGFloat buttonOffset;

@end


@implementation SVTopScrollView

@synthesize nameArray;
@synthesize scrollViewSelectedChannelID;

+ (SVTopScrollView *)shareInstance {
    static SVTopScrollView *_instance;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _instance=[[self alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [[SVGloble shareInstance] globleTopHeight])];
    });
    return _instance;
}

+ (void)setSelectedIndex:(NSInteger)index
{
    SVTopScrollView *_instance = [SVTopScrollView shareInstance];
    UIView *view = [_instance viewWithTag:100+index];
    if (view != nil) {
        UIButton *btn = (UIButton*)view;
        [_instance selectNameButton:btn];
    }
}

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self)
    {
        self.scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(SCROLLVIEW_X_OFFSET, 0, self.frame.size.width - SCROLLVIEW_X_OFFSET, self.frame.size.height)];
        self.scrollView.delegate = self;
        self.backgroundColor = [UIColor clearColor];
        self.scrollView.pagingEnabled = NO;
        self.scrollView.showsHorizontalScrollIndicator = NO;
        self.scrollView.showsVerticalScrollIndicator = NO;
        self.scrollView.backgroundColor = [UIColor clearColor];
        [self addSubview:self.scrollView];
        self.buttonOffset = BUTTONGAP;
        self.labelFont = [UIFont systemFontOfSize:20.0];
        userSelectedChannelID = 100;
        scrollViewSelectedChannelID = 100;
        
        self.buttonOriginXArray = [NSMutableArray array];
        self.buttonWithArray = [NSMutableArray array];
    }
    return self;
}

- (void)initWithNameButtons
{
    if([self.nameArray count] == 0)
    {
        return;
    }
    float xPos = 0;
    userSelectedChannelID = 100;
    scrollViewSelectedChannelID = 100;
    for (UIView* view in self.subviews) {
        if (view.tag > 0) {
            [view removeFromSuperview];
        }
    }
    for (UIView* view in self.scrollView.subviews) {
        if (view.tag > 0) {
            [view removeFromSuperview];
        }
    }
    if (shadowImageView) {
        [shadowImageView removeFromSuperview];
        shadowImageView = nil;
    }
    _buttonOriginXArray = [NSMutableArray array];
    _buttonWithArray = [NSMutableArray array];
    float  buttonWidth = self.scrollView.bounds.size.width/3;
    float buttonHeight = [[SVGloble shareInstance] globleTopHeight];
    for (int i = 0; i < [self.nameArray count]; i++) {
        
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        NSString *title = [self.nameArray objectAtIndex:i];
        
        [button setTag:i+100];
        [button setTitle:title forState:UIControlStateNormal];
        button.titleLabel.font = _labelFont;
        [button setTitleColor:[SVGloble colorFromHexRGB:@"383638"] forState:UIControlStateNormal];
        [button setTitleColor:[UIColor redColor] forState:UIControlStateSelected];
        [button addTarget:self action:@selector(selectNameButton:) forControlEvents:UIControlEventTouchUpInside];
        if (i == 0) {
            button.selected = YES;
            button.titleLabel.font = [UIFont boldSystemFontOfSize:_labelFont.pointSize];
        }
        button.frame = CGRectMake(xPos, 0, buttonWidth, buttonHeight);
        
        [_buttonOriginXArray addObject:@(xPos)];
        
//        xPos += buttonWidth+_buttonOffset;
        xPos += buttonWidth;
        
        [_buttonWithArray addObject:@(button.frame.size.width)];
       
        [self.scrollView addSubview:button];
    }
    
    self.scrollView.contentSize = CGSizeMake(buttonWidth*self.nameArray.count, [[SVGloble shareInstance] globleTopHeight]);
    
    shadowImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, [[_buttonWithArray objectAtIndex:0] floatValue], [[SVGloble shareInstance] globleTopHeight])];
//    [shadowImageView setImage:[UIImage imageNamed:@"public/line.png"]];
    UIView *selectLineView =  [[UIView alloc] initWithFrame:CGRectMake(0, shadowImageView.bounds.size.height-2, shadowImageView.bounds.size.width, 2)];
    selectLineView.backgroundColor = [UIColor redColor];
    [shadowImageView addSubview:selectLineView];
    shadowImageView.contentMode = UIViewContentModeBottom;
    [self addSubview:shadowImageView];
    //横线
    UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(0, self.scrollView.bounds.size.height-0.5, self.scrollView.bounds.size.width, 0.5)];
    lineView.backgroundColor = [UIColor redColor];
    [self.scrollView addSubview:lineView];
}




-(void)setMoreButtonSelectState:(BOOL)state
{
    UIButton *button = (UIButton *)[self viewWithTag:9999];
    UIImageView *iconView = (UIImageView *)[button viewWithTag:999];
    if(state)
    {
       
        button.selected = YES;
        iconView.image = [UIImage imageNamed:@"public/more_qy.png"];
    }
    else
    {
        button.selected = NO;
        iconView.image = [UIImage imageNamed:@"public/more_q.png"];
    }
    
}

-(void)addButtonClick:(UIButton *)button
{
    [self setMoreButtonSelectState:YES];
    if(_svTopDelegate && [_svTopDelegate respondsToSelector:@selector(svTopAddButtonClick)])
    {
        [_svTopDelegate svTopAddButtonClick];
    }
}

//点击顶部条滚动标签
- (void)selectNameButton:(UIButton *)sender
{
    if ([SVRootScrollView shareInstance].ifDragging == YES) {
        return;
    }
    [self adjustScrollViewContentX:sender];
    
    //如果更换按钮
    if (sender.tag != userSelectedChannelID) {
        //取之前的按钮
        UIButton *lastButton = (UIButton *)[self viewWithTag:userSelectedChannelID];
        lastButton.selected = NO;
        //赋值按钮ID
        userSelectedChannelID = sender.tag;
    }
    
    //按钮选中状态
    if (!sender.selected) {
        sender.selected = YES;
        
        [UIView animateWithDuration:0.25 animations:^{
            [shadowImageView setFrame:CGRectMake(sender.frame.origin.x, 0, [[_buttonWithArray objectAtIndex:BUTTONID] floatValue], [[SVGloble shareInstance] globleTopHeight])];
            [self setButtonTitleSize:sender.tag];
        } completion:^(BOOL finished) {
            if (finished) {
                //设置新闻页出现
                [[SVRootScrollView shareInstance] setContentOffset:CGPointMake(BUTTONID*[UIScreen mainScreen].bounds.size.width, 0) animated:NO];
                [[SVRootScrollView shareInstance] refleshPageTitle];
                //赋值滑动列表选择频道ID
                scrollViewSelectedChannelID = sender.tag;
            }
        }];
        
    }
    //重复点击选中按钮
    else {
        
    }
}

- (void)adjustScrollViewContentX:(UIButton *)sender
{
    float originX = [[_buttonOriginXArray objectAtIndex:BUTTONID] floatValue];
    float width = [[_buttonWithArray objectAtIndex:BUTTONID] floatValue];
    if (sender.frame.origin.x - self.scrollView.contentOffset.x > CONTENTSIZEX-(/*_buttonOffset/2.0+*/width)) {
        [self.scrollView setContentOffset:CGPointMake(originX + width - CONTENTSIZEX, 0)  animated:YES];
    }
    
    if (sender.frame.origin.x - self.scrollView.contentOffset.x < 5) {
        [self.scrollView setContentOffset:CGPointMake(originX,0)  animated:YES];
    }
}

//滚动内容页顶部滚动
- (void)setButtonUnSelect
{
    //滑动撤销选中按钮
    UIButton *lastButton = (UIButton *)[self viewWithTag:scrollViewSelectedChannelID];
    lastButton.selected = NO;
}

- (void)setButtonSelect
{
    if (_buttonWithArray.count == 0) {
        return;
    }
    
    //滑动选中按钮
    UIButton *button = (UIButton *)[self viewWithTag:scrollViewSelectedChannelID];
    
    [self setButtonTitleSize:button.tag];
    if (!button.selected) {
        button.selected = YES;
        userSelectedChannelID = button.tag;
    }
    [UIView animateWithDuration:0.25 animations:^{
        [shadowImageView setFrame:CGRectMake(button.frame.origin.x, 0, [[_buttonWithArray objectAtIndex:button.tag-100] floatValue], [[SVGloble shareInstance] globleTopHeight])];
        [self setButtonTitleSize:button.tag];
    } completion:^(BOOL finished) {
        if (finished) {
            if (!button.selected) {
                button.selected = YES;
                userSelectedChannelID = button.tag;
            }
        }
    }];
    
}

- (void)setButtonTitleSize:(int)tag
{
    for (int i=0; i<_buttonWithArray.count; i++) {
        UIButton *btn = (UIButton*)[self viewWithTag:i+100];
        if (i+100 == tag) {
            btn.titleLabel.font = [UIFont boldSystemFontOfSize:_labelFont.pointSize];
        }
        else {
            btn.titleLabel.font = [UIFont systemFontOfSize:_labelFont.pointSize];
        }
    }
}

-(void)setScrollViewContentOffset
{
    float originX = [[_buttonOriginXArray objectAtIndex:BUTTONSELECTEDID] floatValue];
    float width = [[_buttonWithArray objectAtIndex:BUTTONSELECTEDID] floatValue];
    
    if (originX - self.scrollView.contentOffset.x > CONTENTSIZEX-(_buttonOffset/2.0+width)) {
        [self.scrollView setContentOffset:CGPointMake(originX + width - CONTENTSIZEX, 0)  animated:YES];
    }
    
    if (originX - self.scrollView.contentOffset.x < 5) {
        [self.scrollView setContentOffset:CGPointMake(originX,0)  animated:YES];
    }
}
-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    CGPoint offset = scrollView.contentOffset;
    NSLog(@"SVTopScroollView scrollViewDidScroll offset.x = %f",offset.x);
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
    // Drawing code
}
*/

@end
